import 'dart:async';

import 'package:flutter/material.dart';
import 'package:noise_meter/noise_meter.dart';

class Noise extends StatefulWidget {
  const Noise({Key key}) : super(key: key);

  @override
  _NoiseState createState() => _NoiseState();
}

class _NoiseState extends State<Noise> {
  ///监听噪音流
  StreamSubscription<NoiseReading> _noiseSubscription;

  ///噪音计
  NoiseMeter _noiseMeter;

  ///噪音大小
  double _db = 0;

  ///等级颜色
  Color _color;

  ///字体大小
  double _fontSize;

  ///是否出错
  bool _err = false;

  ///开始监听
  Future<void> _startRecorder() async {
    try {
      _noiseMeter = NoiseMeter();
      _noiseSubscription = _noiseMeter.noiseStream.listen(_onData);
      _color = Colors.green;
      _fontSize = 50;
    } catch (exception) {
      print('error:$exception');
    }
  }

  ///数据改变
  void _onData(NoiseReading noiseReading) {
    if (noiseReading.meanDecibel < 0) {
      setState(() => _err = true);
      return;
    } else if (noiseReading.meanDecibel < 40) {
      _color = Colors.green;
      _fontSize = 50;
    } else if (noiseReading.meanDecibel < 60) {
      _color = const Color(0xffc4811d);
      _fontSize = 60;
    } else {
      _color = Colors.red;
      _fontSize = 70;
    }

    if (_db < 1000) {
      setState(() {
        _err = false;
        _db = noiseReading.meanDecibel;
      });
    }
  }

  ///结束监听
  void _stopRecorder() async {
    try {
      if (_noiseSubscription != null) {
        _noiseSubscription.cancel();
        _noiseSubscription = null;
      }
    } catch (err) {
      print('stopRecorder error: $err');
    }
  }

  @override
  void initState() {
    super.initState();

    _startRecorder();
  }

  @override
  void dispose() {
    _stopRecorder();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Hero(
      tag: 'item1',
      child: Material(
        color: Colors.black,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                AnimatedDefaultTextStyle(
                  child: Text('${_db.floor()}'),
                  style: TextStyle(
                    fontSize: _fontSize,
                    color: _color,
                    fontWeight: FontWeight.bold,
                  ),
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.ease,
                ),
                const Text(
                  'dB',
                  style: const TextStyle(
                    fontSize: 20,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
            _err
                ? Text(
                    '设备不支持',
                    style: const TextStyle(
                      fontSize: 8,
                      color: Colors.grey,
                      fontWeight: FontWeight.normal,
                    ),
                  )
                : Container(),
          ],
        ),
      ),
    );
  }
}
